<?php
namespace wof;

use wof\Letter;

class Quiz {
    private $db;
    private $i_CatId;
    public $a_PlayerData;
    
    public function __construct($i_CatId, $a_PlayerData) {
        $this->db = new DBConfig;
        $this->i_CatId = $i_CatId;
        $this->a_PlayerData = $a_PlayerData;
        $this->a_PlayerData["cat-id"] = $i_CatId;
    }
    
    /* Generate question */
    public function generate_quiz($a_SelectedQuiz) {
        // Get list quiz Id
        $o_ListQuizId = $this->o_fListQuestionId($this->i_CatId,$a_SelectedQuiz);
        $i_QuizTotal = count((array)$o_ListQuizId);
        
        // Random select quiz Id
        $i_SelectQuiz = rand(0, $i_QuizTotal - 1);
        $i_SelectQuizId = $o_ListQuizId->{$i_SelectQuiz};
        
        // Select quiz from quiz_id
        $o_SelectQuestion = $this->o_fGetQuestion($i_SelectQuizId);
        
        // Store answer to global
        $this->a_PlayerData["quiz-answer"] = $o_SelectQuestion->{'quiz_answer'};
        $this->a_PlayerData["select-quiz-id"][] = $i_SelectQuizId;
        
        // Generate letter positions
        $o_Letter = new Letter($this->a_PlayerData, "");
        $sz_ReturnValue = $o_SelectQuestion->{'quiz_question'} . "%%S%%" . $o_Letter->a_fGenerateLetterMatrix();
        $this->a_PlayerData = $o_Letter->a_PlayerData;
        return $sz_ReturnValue;
    }
    
    /* Get question list from DB */
    public function o_fListQuestionId($i_CatId = 0, $a_SelectedQuiz = array())
    {
        $o_Questions = new \stdClass();
        $sql="SELECT quiz_id FROM wof_quiz WHERE quiz_cat_id = ?";
        /* Filter by selected question previous round */
        if ($a_SelectedQuiz) {
            for ($i=0;$i<count($a_SelectedQuiz);$i++) {
                $sql.=" AND quiz_id <> ?";
            }
        }
        $statement = $this->db->pdo->prepare($sql);
        if ($a_SelectedQuiz) {
            $a_Vars = array_merge(array($i_CatId),$a_SelectedQuiz);
            $statement->execute($a_Vars);
        }
        else {
            $statement->execute(array($i_CatId));
        }
        
        $i= 0;
        while ($row = $statement->fetch())
        {
            $o_Questions->{$i} = $row['quiz_id'];
            $i++;
        }
        
        return $o_Questions;
    }
    
    /* Select question from DB */
    public function o_fGetQuestion($i_QuizId = 0)
    {
        $o_Questions = new \stdClass();
        $sql="SELECT * FROM wof_quiz WHERE quiz_id = ?";
        $statement = $this->db->pdo->prepare($sql);
        $statement->execute(array($i_QuizId));
        
        $o_Questions = $statement->fetchObject();
        
        return $o_Questions;
    }
}
?>